<template>
  <div class="whiteDialog">
    <el-dialog :visible.sync="dialogVisible" @close="dialogVisible = false"
               :width="width"
               :append-to-body="appendToBody" :close-on-click-modal="false">
      <header>{{dialogTitle}}</header>
      <el-form :ref="formName" :rules="formRules" class="small-space" :model="form" :label-position="labelPosition"
               :label-width="labelWidth">
        <slot>
        </slot>
      </el-form>
      <div v-if="footerVisible" slot="footer" class="dialog-footer">
        <auth-button size="" :label="$t('common.close')" @click="dialogVisible = false" :menuCode="menuCode" :perms="closePerms"></auth-button>
        <auth-button v-if="editModel!=='V' && saveFlag" size="" type="primary" :label="$t('common.save')" :loading="loading" @click="save" :menuCode="menuCode" :perms="savePerms"></auth-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
    import { Message } from 'element-ui'
    import AuthButton from '@/components/auth/authButton'
    // const editTitleMap = {
    //   'V': '查看',
    //   'E': '编辑',
    //   'C': '创建'
    // }
    export default{
      components: {AuthButton},
      props: {
        // 所属菜单Code-->全局唯一
        menuCode: {
          type: String,
          default: null
        },
        // 按钮权限标识，外部使用者传入
        savePerms: {
          type: String,
          default: null
        },
        // 按钮权限标识，外部使用者传入
        closePerms: {
          type: String,
          default: null
        },
        visible: {
          required: true,
          type: [Boolean],
          default: function () {
            return false
          }
        },
        appendToBody: {  // 是否是内层的嵌套dialog
          type: Boolean,
          default: function () {
            return false
          }
        },
        editModel: {
          // required: true,
          type: [Number, String],
          default: 'V'
        },
        form: {
          // required: true, // 这个地方不应该必须，type不应定死？
          type: [Object],
          default: function () {
            return {}
          }
        },
        formRules: {
          type: [Object]
        },
        labelWidth: {
          default: function () {
            return '120px'
          }
        },
        width: {
          default: function () {
            return '70%'
          }
        },
        title: {
          type: [String],
          required: true
        },
        autoSave: {
          type: [Boolean],
          default: function () {
            return true
          }
        },
        api: {
          type: [Object],
          // required: true
          default: function () {
            return {}
          }
        },
        loadRemote4Edit: {
          type: [Boolean],
          default: function () {
            return true
          }
        },
        labelPosition: {
          type: [String],
          default: function () {
            return 'right'
          }
        },
        footerVisible: {
          type: [Boolean],
          default: function () {
            return true
          }
        },
        beforeSave: {
          type: [Boolean],
          required: false
        },
        createCode: {
          type: String,
          default () {
            return ''
          }
        },
        editCode: {
          type: String,
          default () {
            return ''
          }
        },
        reviewCode: {
          type: String,
          default () {
            return ''
          }
        },
        saveFlag: {
          type: Boolean,
          default () {
            return true
          }
        }
      },
      data: function () {
        return {
          formName: 'editForm',
          loading: false
        }
      },
      computed: {
        dialogTitle: function () {
          return this.title
        },
        dialogVisible: {
          get: function () {
            return this.visible
          },
          set: function (value) {
            this.$emit('update:visible', value)
          }
        }
      },
      methods: {
        resetForm: function () {
          let $this = this
                // $this.$refs[this.formName].resetFields()
          $this.$refs[this.formName].clearValidate()
        },
        loadData: function () {
          if (this.editModel === 'V') {
            return
          }
                // 不从远程加载
          if (!this.loadRemote4Edit) {
            return
          }
          if (this.form && this.form.id && (this.form.id !== 0 || this.form.id !== '0')) {
            let id = this.form.id
            let $this = this
            return new Promise((resolve, reject) => {
              $this.api.get(id).then(res => {
                Object.assign($this.form, res.data)
              })
            })
          }
        },
        save: function () {
          let $this = this
          this.$refs[this.formName].validate((valid) => {
            if (valid) {
              $this.loading = true
              if (!$this.autoSave) {
                $this.$emit('onSaved', this.form)
                return false
              }
              if ($this.beforeSave) {
                $this.$emit('beforeSaved', $this.form)
              }
              if ($this.editModel === 'C') {
                $this.api.create($this.form).then(res => {
                  if ($this.success) {
                    $this.createCode === '' ? $this.success(`新增${this.title}成功`) : $this.message(res, $this.createCode)
                    // $this.message(res, $this.createCode)
                  } else {
                    Message({
                      message: `新增${$this.title}成功`,
                      type: 'success',
                      duration: 3 * 1000
                    })
                  }
                  $this.$emit('onSave', this.form)
                  $this.loading = false
                  $this.dialogVisible = false
                }).catch(res => {
                  $this.loading = false
                  this.$emit('errSave', res)
                })
              } else if (this.editModel === 'E' || this.editModel === 'R') {
                $this.api.update(this.form.keyId, this.form).then(res => {
                  if ($this.success && $this.editModel === 'E') {
                                    // $this.success(`修改${this.title}成功`)
                    $this.editCode === '' ? $this.success(`修改${this.title}成功`) : $this.message(res, $this.editCode)
                  } else if ($this.success && $this.editModel === 'R') {
                    $this.reviewCode === '' ? $this.success(`复核${this.title}成功`) : $this.message(res, $this.reviewCode)
                  }
                  $this.$emit('onSave', this.form)
                  $this.dialogVisible = false
                  $this.loading = false
                }).catch(res => {
                  this.$emit('errSave', res)
                  $this.loading = false
                })
              }
            } else {
              if ($this.error) {
                $this.error('表单填写错误，请检查')
              } else {
                Message({
                  message: '表单填写错误，请检查',
                  type: 'error',
                  duration: 3 * 1000
                })
              }
              return false
            }
          })
        }
      },
      watch: {
        form: function (value, old) {
          this.loadData()
        },
        dialogVisible: function (value, old) {
          this.$nextTick(() => {
            this.resetForm()
          })
        }
      }
    }
</script>
<style>
  .whiteDialog .el-dialog__header {
    padding: 10px 20px;
    text-align: center;
    background: white;
  }
  .whiteDialog header{
    text-align: center;
    font-size: 16px;
    margin-bottom: 10px;
  }
</style>
